<template>
	<div>
		<xn-form-container
			:title="formData.id ? '编辑' : '新增'"
			:width="1000"
			:visible="visible"
			:destroy-on-close="true"
			@close="onClose"
		>
			<a-form
				:wrapper-col="{ span: 16 }"
				:label-col="{ span: 8 }"
				autocomplete="off"
				labelAlign="right"
				ref="formRef"
				:model="formData"
				:rules="formRules"
			>
				<a-row>
					<a-col :span="12">
						<a-form-item label="分摊方式" name="shareMethod">
							<a-select :getPopupContainer="trigger => trigger.parentNode" placeholder="请选择分摊方式" v-model:value="formData.shareMethod" :options="shareMethod">
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row>
					<a-col :span="24">
						<a-row style="margin-bottom: 12px">
							<a-space size="middle">
								<a-button type="primary" @click="addProduct()">
									<PlusOutlined />
									新增
								</a-button>
								<a-popconfirm title="是否删除?" @confirm="removeGoods()">
									<a-button type="remove" danger>
										<LineOutlined />
										删除
									</a-button>
								</a-popconfirm>
								<a-button @click="impExpRef.onOpen()" ghost type="primary"> 导入 </a-button>
							</a-space>
						</a-row>
						<a-table
							:row-selection="options.rowSelection"
							:pagination="false"
							:columns="goodsColumns"
							:data-source="formData.costSharingDetailAddParamList"
							:scroll="{ x: 1000 }"
						>
							<template #bodyCell="{ index, record, column }">
								<template v-if="column.dataIndex === 'index'">
									<span>{{ index + 1 }}</span>
								</template>

								<template v-if="column.dataIndex === 'productStorageCode'">
									<a-input :style="{ width: column.width }" v-model:value="record.productStorageCode" />
								</template>
								<template v-if="column.dataIndex === 'productNo'">
									<a-input :style="{ width: column.width }" v-model:value="record.productNo" />
								</template>

								<template v-if="column.dataIndex === 'unit'">
									<a-input :style="{ width: column.width }" v-model:value="record.unit" />
								</template>
								<template v-if="column.dataIndex === 'num'">
									<a-input
										@input="onNumberChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.num"
									/>
								</template>
								<template v-if="column.dataIndex === 'workHours'">
									<a-input
										@input="onWorkHoursChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.workHours"
									/>
								</template>

								<template v-if="column.dataIndex === 'artificial'">
									<a-input
										@input="onChange(record, 'artificial', 'artificialTotal')"
										:style="{ width: column.width }"
										v-model:value="record.artificial"
									/>
								</template>

								<template v-if="column.dataIndex === 'auxiliary'">
									<a-input
										@input="onChange(record, 'auxiliary', 'auxiliaryTotal')"
										:style="{ width: column.width }"
										v-model:value="record.auxiliary"
									/>
								</template>

								<template v-if="column.dataIndex === 'manufacture'">
									<a-input
										@input="onChange(record, 'manufacture', 'manufactureTotal')"
										:style="{ width: column.width }"
										v-model:value="record.manufacture"
									/>
								</template>

								<template v-if="column.dataIndex === 'depreciation'">
									<a-input
										@input="onChange(record, 'depreciation', 'depreciationTotal')"
										:style="{ width: column.width }"
										v-model:value="record.depreciation"
									/>
								</template>

								<template v-if="column.dataIndex === 'hydropower'">
									<a-input
										@input="onChange(record, 'hydropower', 'hydropowerTotal')"
										:style="{ width: column.width }"
										v-model:value="record.hydropower"
									/>
								</template>
								<template v-if="column.dataIndex === 'other'">
									<a-input
										@input="onChange(record, 'other', 'otherTotal')"
										:style="{ width: column.width }"
										v-model:value="record.other"
									/>
								</template>
							</template>
						</a-table>
					</a-col>
				</a-row>
				<div style="margin: 15px 0 12px 0">
					<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
				</div>
				<a-row>
					<a-col :span="8">
						<a-form-item label="辅助材料合计" name="auxiliaryTotal">
							<a-input disabled v-model:value="formData.auxiliaryTotal" placeholder="请输入辅助材料合计" allow-clear />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="制造费用合计" name="manufactureTotal">
							<a-input
								disabled
								v-model:value="formData.manufactureTotal"
								placeholder="请输入辅助材料合计"
								allow-clear
							/>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="折旧费用合计" name="depreciationTotal">
							<a-input
								disabled
								v-model:value="formData.depreciationTotal"
								placeholder="请输入折旧费用合计"
								allow-clear
							/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="8">
						<a-form-item label="水电费用合计" name="hydropowerTotal">
							<a-input disabled v-model:value="formData.hydropowerTotal" placeholder="请输入水电费用合计" allow-clear />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="其它费用合计" name="otherTotal">
							<a-input disabled v-model:value="formData.otherTotal" placeholder="请输入其它费用合计" allow-clear />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="直接人工合计" name="artificialTotal">
							<a-input disabled v-model:value="formData.artificialTotal" placeholder="请输入直接人工合计" allow-clear />
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>

			<template #footer>
				<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
			</template>
		</xn-form-container>
		<xn-import
			:upload-request="(params) => onUpload(params)"
			@download-template="onDownload"
			ref="impExpRef"
		></xn-import>
	</div>
</template>

<script setup name="dbsForm">
	import { required } from '@/utils/formRules'
	import { message } from 'ant-design-vue'
	import { toRaw } from 'vue'
	import dayjs from 'dayjs'
	import costsharingApi from '@/api/produce/costsharingApi'
	import tool from '@/utils/tool'
	import XnImport from '@/components/XnImport/index.vue'
	import costSharingDetailApi from '@/api/produce/costsharingdetailApi'
	import downloadUtil from '@/utils/downloadUtil'
	const impExpRef = ref()
	const shareMethod = tool.dictList('shareMethod')
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const submitLoading = ref(false)
	const onDownload = () => {
		costSharingDetailApi
			.downloadImportCostTemplate()
			.then((res) => {
				downloadUtil.resultDownload(res)
			})
			.catch(() => {})
	}
	const onUpload = (params) => {
		return new Promise((resolve, rejected) => {
			costSharingDetailApi
				.import(params)
				.then((res) => {
					resolve()
					res.forEach((it) => {
						it['key'] = tool.snowyUuid()
					})
					let detailList = formData.value.costSharingDetailAddParamList
					if (!detailList) {
						detailList = []
					}
					formData.value.costSharingDetailAddParamList = detailList.concat(res)
					calculateAll()
				})
				.catch((e) => {
					rejected(e)
				})
		})
	}
	const onNumberChange = (record) => {
		let value = parseInt(record.num.replace(/[^\d]+/g, ''))
		if (isNaN(value)) {
			record.num = ''
		} else {
			record.num = value
		}
	}
	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		formData.value = {}
		if (record) {
			let params = { ...record }
			formData.value = params
			loadDetail(params)
		} else {
			formData.value.deliveryDate = ref(dayjs())
		}
	}

	const loadDetail = (record) => {
		costsharingApi
			.detail({
				id: record.id
			})
			.then((res) => {
				res.costSharingDetailList.forEach((element) => {
					element['key'] = element['materialId']
					element['name'] = ['name']
				})
				formData.value.costSharingDetailAddParamList = res.costSharingDetailList
			})
			.catch(() => {})
	}

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const selectedRowKeys = ref([])

	const formatPrice = (text) => {
		return text.match(/^\d*(\.?\d{0,2})/g)[0] || null
	}
	const onWorkHoursChange = (record) => {
		//let value = record.workHours.replace(/[^\d]+/g, '')
		let value = formatPrice(record.workHours)
		// record.workHours = value
	}

	const onChange = (record, field, totalField) => {
		let value = formatPrice(record[field])
		record[field] = value
		let total = calculate(field)
		formData.value[totalField] = total
	}

	const calculateAll = () => {
		let fields = ['artificial', 'auxiliary', 'manufacture', 'depreciation', 'hydropower', 'other']
		for (let field of fields) {
			let total = calculate(field)
			formData.value[`${field}Total`] = total
		}
	}

	const calculate = (field) => {
		let detailList = formData.value.costSharingDetailAddParamList || []
		let amount = 0
		for (let it of detailList) {
			if (it[field]) {
				let fieldValue = parseFloat(it[field])
				if (!isNaN(fieldValue)) {
					amount += fieldValue
				}
			}
		}
		return amount > 0 ? parseFloat(amount.toFixed(2)) : amount
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		shareMethod: [required('请选择分摊方式')]
	}
	const addProduct = () => {
		if (!formData.value.costSharingDetailAddParamList) {
			formData.value.costSharingDetailAddParamList = []
		}
		formData.value.costSharingDetailAddParamList.push({
			key: tool.snowyUuid()
		})
	}

	const removeGoods = () => {
		let datas = formData.value.costSharingDetailAddParamList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['key'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		calculateAll()
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				let orderList = toRaw(formData.value.costSharingDetailAddParamList) || []
				if (orderList.length <= 0) {
					message.error('请商品明细')
					return
				}
				let msg = null
				let itemRules = [
					{
						field: 'productStorageCode',
						error: '产品入库单号不能为空!'
					},

					{
						field: 'num',
						error: '产品数量不能为空!'
					}
				]
				for (let i = 0; i < orderList.length; i++) {
					for (let rule of itemRules) {
						let item = orderList[i]
						let itemValue = item[rule['field']]
						if (!itemValue) {
							msg = `第${i + 1}行${rule['error']}`
							break
						}
					}
				}
				if (msg) {
					message.error(msg)
					return
				}
				submitLoading.value = true
				let params = { ...formData.value }
				if (params.id) {
					params.costSharingDetailEditParamList = params.costSharingDetailAddParamList.map((it) => {
						return {
							id: it['id'],
							productStorageCode: it['productStorageCode'],
							materialId: it['materialId'],
							workHours: it['workHours'],
							artificial: it['artificial'],
							auxiliary: it['auxiliary'],
							manufacture: it['manufacture'],
							depreciation: it['depreciation'],
							hydropower: it['hydropower'],
							other: it['other']
						}
					})
					params.costSharingDetailAddParamList = undefined
				}
				costsharingApi
					.addOrEdit(params)
					.then(() => {
						visible.value = false
						emit('successful')
					})
					.catch(() => {})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

	const goodsColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '产品入库单号',
			width: 120,
			dataIndex: 'productStorageCode',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品代码',
			width: 120,
			dataIndex: 'productNo',
			align: 'center',
			ellipsis: true
		},

		{
			title: '单位',
			width: 120,
			dataIndex: 'unit',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品数量',
			width: 100,
			dataIndex: 'num',
			align: 'center',
			ellipsis: true
		},
		{
			title: '工时(小时)',
			width: 100,
			dataIndex: 'workHours',
			align: 'center',
			ellipsis: true
		},
		{
			title: '直接人工',
			width: 100,
			dataIndex: 'artificial',
			align: 'center',
			ellipsis: true
		},
		{
			title: '辅助材料',
			width: 100,
			dataIndex: 'auxiliary',
			align: 'center',
			ellipsis: true
		},
		{
			title: '制造费用',
			width: 100,
			dataIndex: 'manufacture',
			align: 'center',
			ellipsis: true
		},
		{
			title: '折旧费用',
			width: 100,
			dataIndex: 'depreciation',
			align: 'center',
			ellipsis: true
		},
		{
			title: '水电费用',
			width: 100,
			dataIndex: 'hydropower',
			align: 'center',
			ellipsis: true
		},
		{
			title: '其它费用',
			width: 100,
			dataIndex: 'other',
			align: 'center',
			ellipsis: true
		}
	]
</script>

<style scoped :type="less"></style>
